<?php


namespace app\store\controller\shop;


use app\api\model\Wxapp as WxappModel;
use app\common\library\wechat\WxPay;
use app\common\model\CourseOrderDetail;
use app\store\controller\Controller;
use app\common\model\CourseOrder as CourseOrderModel;
use app\store\controller\User;
use app\store\model\store\shop\Clerk as ClerkModel;
use app\store\model\store\shop\Coach;
use app\store\model\User as UserModel;
use app\store\model\store\Shop as ShopModel;
use app\common\model\CourseCard as CourseCardModel;
use app\common\service\message\order\Delivery as DeliveryService;
use think\Db;

/**课程卡订单列表
 * Class CourseOrder
 * @package app\store\controller\shop
 */
class CourseOrder extends Controller
{
    public function test(){
$test = \app\common\model\Reservation::detail(['id'=>5]);dump($test->toArray());
        die;
        $config = WxappModel::getWxappCache(10001);
        $noti = new WxPay($config);
        $res = $noti->refund('4200001768202303017563337756','0.01','0.01');
        if ($res){
            echo '退款成功';
        }
    }
    public function tui(){
        $service = new DeliveryService();
        $res = $service->sendWxSubMsg2(10001,[
//            'touser' => 'oXDNX5AqWuODALg47XHpi-Hj0MAc',
            'touser' => 'oXDNX5JqkI6sJxfR44WoHc6J1BFc',
            'template_id' => '9CqeF6dltymSS_J2wDDMo0aaWhWIJRwNRNaEz7CKTWM',
            'page' => '',
            'data' => [
                // 订单号
                'thing6' => ['value' => '23232323'],
                // 商品名称
                'thing13' => ['value' => '343434'],
                // 收货人
                'name9' => ['value' => '测试教练'],
                // 收货地址
                'thing2' => ['value' => '32323'],
                // 物流公司
                'date7' => ['value' =>date('Y-m-d')],
            ],
        ]);
        dump($res);
    }
    public function index(){
       $model = new CourseOrderModel();
       $shopList = $this->shopList();
       $list = $model->getPageList(array_merge(['is_active'=>1,'listRows'=>10],$this->request->param()));
       $status = [
           0=>'待支付',
           1=>'已支付',
           2=>'已生效',
           3=>'使用完',
           4=>'已过期',
           5=>'已停用'
       ];
        $status_color = [
            0=>'secondary',
            1=>'success',
            2=>'primary',
            3=>'warning',
            4=>'danger',
            5=>'danger'
        ];
        $order_source = [
            10=>'正常购买',
            20=>'后台补发',
        ];
//       dump($list->toArray());die;
        return $this->fetch('index', compact('list','status','shopList','order_source','status_color'));
    }

    /**
     * @title 后台补卡
     * @param $user_id
     * @author Qian
     * Time: 2023/3/1  15:36
     */
    public function add($user_id){
        if (!$this->request->isAjax()){
            $cardModel = new CourseCardModel();
            $user = UserModel::detail(['user_id'=>$user_id]);
            $shop_id = $this->store['user']['shop_user_id'];
            $where = [];
            if ($shop_id){
                $where['shop_id']=$shop_id;
            }
            $where['status'] = 0;
            $list = $cardModel->getAllList($where);
            //教练列表
            $getList = $this->getCoachClerk();
            //店员列表
            $coach = json_encode($getList['coach']->toArray(),true);
            $clerk = json_encode($getList['clerk']->toArray(),true);
            return $this->fetch('add',compact('list','user','coach','clerk'));
        }
        $model = new CourseOrderModel();
        if ($model->addOrder($this->postData('order'))) {
            return $this->renderSuccess('添加成功', url('shop.course_order/index'));
        }
        return $this->renderError($model->getError() ?: '添加失败');

    }

    /**
     * @title 扣除卡次数
     * @param $user_id
     * @author Qian
     * Time: 2023/5/30  17:42
     */
    public function reduce($user_id){
        if (!$this->request->isAjax()){
            $courseOrderModel = new CourseOrderModel();
            $user = UserModel::detail(['user_id'=>$user_id]);
            $shop_id = $this->store['user']['shop_user_id'];
            $course = (new \app\common\model\Course())->where(['is_delete'=>0])->with(['image','image.file'])->select();

            $where = [];
            if ($shop_id){
                $where['shop_id']=$shop_id;
            }
            $where['is_active'] = 1;//已激活
            $where['is_delete'] = 0;//未删除
            $list_1 = $courseOrderModel->getList($user_id,array_merge(['type'=>1],$where)); //私教
            $list_2 = $courseOrderModel->getList($user_id,array_merge(['type'=>2],$where)); //团课
            //教练列表
            $getList = $this->getCoachClerk();
            //店员列表
            $coach = $getList['coach'];
            $start = "08:00";
            $end = "20:00";
            $arr = [];
            while ($start <= $end){
                array_push($arr,date('H:i',strtotime($start)));
                $start = date('H:i',strtotime("$start + 1 hour"));
            }
            $list_1 = json_encode($list_1->toArray(),true);
            $list_2 = json_encode($list_2->toArray(),true);
            return $this->fetch('reduce',compact('list_1','list_2','user','coach','arr','course'));
        }
        $model = new CourseOrderModel();
        if ($model->reduceOrder($this->postData('order'))) {
            return $this->renderSuccess('操作成功', url('shop.course_order/index'));
        }
        return $this->renderError($model->getError() ?: '操作失败');

    }

    public function getCoachClerk(){
        //所属门店的教练
        $shop_user_id = $this->store['user']['shop_user_id'];
        $user_type = $this->store['user']['user_type'];
        $where = [];
        $shop_id = 0;
        if ($user_type == 2){
            //门店
            $where['shop_id']=$shop_user_id;
            $shop_id = $shop_user_id;
        }elseif ($user_type == 3){
            //教练
            $where['coach_id'] = $shop_user_id;
            $coach_detail = Coach::detail(['coach_id'=>$shop_user_id]);
            $shop_id = $coach_detail['shop_id'];
        }
        $model = new Coach();
        $model2 = new ClerkModel();
        $coach = $model->getAllList($where);
        $clerk = $model2->getAllList(-1,$shop_id);
        return ['coach'=>$coach,'clerk'=>$clerk];
    }

    /**
     * @title 补发列表
     * @author Qian
     * Time: 2023/3/3  14:39
     */
    public function NewlyList(){
        $model = new CourseOrderModel();
        $shopList = $this->shopList();
        $list = $model->getPageList(array_merge(['order_source'=>20],$this->request->param()));
        $status = [
            0=>'待支付',
            1=>'待使用',
            2=>'已生效',
            3=>'使用完',
            4=>'已过期',
            5=>'已停用'
        ];
        $order_source = [
            10=>'正常购买',
            20=>'后台补发',
        ];
        return $this->fetch('newly', compact('list','status','shopList','order_source'));
    }

    public function newlyAdd(){
        if (!$this->request->isAjax()){
            $cardModel = new CourseCardModel();
            $shop_id = $this->store['user']['shop_user_id'];
            $where = [];
            if ($shop_id){
                $where['shop_id']=$shop_id;
            }
            $where['status'] = 0; //全部课程
            $list = $cardModel->getAllList($where);
            $getList = $this->getCoachClerk();
            //店员列表
            $coach = json_encode($getList['coach']->toArray(),true);
            $clerk = json_encode($getList['clerk']->toArray(),true);
            return $this->fetch('newlyadd',compact('list','coach','clerk'));
        }
        $model = new CourseOrderModel();
        if ($model->newlyOrder($this->postData('order'))) {
            return $this->renderSuccess('添加成功', url('shop.course_order/NewlyList'));
        }
        return $this->renderError($model->getError() ?: '添加失败');

    }

    /**
     * @title 删除补发卡
     * @param $order_id
     * @author Qian
     * Time: 2023/3/3  15:59
     */
    public function newlyDelete($order_id){
        if ($this->request->isAjax()){
            $model = CourseOrderModel::detail(['order_id'=>$order_id]);
            if (!$model->setDelete($order_id)) {
                return $this->renderError($model->getError() ?: '删除失败');
            }
            return $this->renderSuccess('删除成功');
        }
    }

    public function shopList(){
        $shop_id = $this->store['user']['shop_user_id'];
        $where=[];
        if ($shop_id){
            $where['shop_id']=$shop_id;
        }
        return ShopModel::getAllList($where);
    }

    /**
     * @param $course_order_id
     * @param $status 5停用 0待付款 1已付款 2生效 3使用完 4已过期
     * @return array|bool|void
     */
    public function stop($course_order_id, $status)
    {
        if ($this->request->isAjax()) {
            $model = CourseOrderDetail::detail(['course_order_id' => $course_order_id]);
            if ($model['card_status'] == 2 && $status == 5) { // 停用
                $update = [
                    'stop_time' => strtotime(date('Y-m-d') . '00:00:00 ', time()),
                    'card_status' => 5
                ];
                if ($model->allowField(true)->save($update)) {
                    return $this->renderSuccess('已停用');
                }

            }
            if ($model['card_status'] == 5 && $status == 2) { // 启用
                // 计算停用时间 到现在到时间差
                $now = strtotime(date('Y-m-d') . '00:00:00 ', time());
                $diff = $now - $model['stop_time'];
                $update = [
                    'card_status' => 2,
                    'expire_time' => $model['expire_time'] + $diff,
                    //'stop_time' => 0
                ];
                if ($model->allowField(true)->save($update)) {
                    return $this->renderSuccess('已启用');
                }

            }
            return $this->renderError(($status == 2) ? '启用失败' : '停用失败');
        }
    }

    /**
     * @title 删除课程卡
     * @param $course_order_id
     * @author Qian
     * Time: 2023/5/29  15:21
     */
    public function del($course_order_id){
        if ($this->request->isAjax()) {
            $model = CourseOrderDetail::detail(['course_order_id' => $course_order_id]);
            if ($model['card_status'] != 1){
                return $this->renderError('改课程卡已经使用过了，不可删除');
            }
            Db::startTrans();
            try {
                $model->allowField(true)->save(['is_delete'=>1]);
                (new \app\common\model\CourseOrder())->where(['order_id'=>$model['order_id']])->update(['is_delete'=>1]);
                Db::commit();
                return $this->renderSuccess('删除成功');
            }catch (\Exception $exception){
                Db::rollback();
                return $this->renderError('删除失败');
            }
        }
    }

    /**
     * @title 导出课程卡
     * @author Qian
     * Time: 2023/6/20  9:28
     */
    public function export(){
        $model = new CourseOrderModel();
        $model->exportList($this->request->param());
    }
}